<template>
  <div class="PageMypetProfile">
    <van-nav-bar
      title="profile"
      :fixed="true"
      :safe-area-inset-top="true"
      :placeholder="true"
      :border="false"
      @click-left="onClickLeft"
    >
      <template #left>
        <van-icon
          size="18"
          style="font-weight: bold"
          color="#000"
          name="arrow-left"
        />
      </template>
    </van-nav-bar>
    <div class="PageMypetProfile_group">
      <van-cell-group inset>
        <!-- 头像单元格 -->
        <van-cell @click="triggerFileInput" center title="Photo" is-link>
          <template #value>
            <!-- 显示用户头像或默认图标 -->
            <img
              v-if="avatarUrl"
              :src="avatarUrl"
              class="avatar-image"
              alt="User Avatar"
            />
            <van-icon v-else class="iconfont icon-user" size="18" />
          </template>
        </van-cell>
        <!-- 隐藏的文件输入 -->
        <input
          type="file"
          ref="fileInput"
          accept="image/*"
          style="display: none"
          @change="handleAvatarChange"
        />
        <van-cell
          @click="ShowFn('NameShow')"
          :value="inputNameText"
          title="Name"
          is-link
        />
        <van-cell
          :value="phoneNumberText"
          @click="ShowFn('PhoneNumber')"
          title="Phone Number"
          is-link
        />
        <van-cell title="My Address" value="0" is-link />
      </van-cell-group>
      <!-- 头像选择弹窗 -->
      <van-action-sheet
        v-model:show="show"
        :actions="actions"
        cancel-text="Cancel"
        close-on-click-action
        @select="onActionSelect"
      />
      <!-- Name  弹窗 -->
      <!-- 姓名编辑弹窗 -->
      <van-popup
        v-model:show="NameShowNumber"
        closeable
        close-icon="close"
        position="bottom"
        round
        :style="{ height: '70%' }"
      >
        <div class="van_popup__title">
          <h3>{{ popupTitle }}</h3>
        </div>
        <div class="van_popup__content">
          <van-field
            type="text"
            ref="inputField"
            v-model="inputValue"
            :error-message="phoneError"
            :error="!!phoneError"
            placeholder="请输入内容"
          />
        </div>
        <div class="van_popup__confirm">
          <van-button @click="SaveSubmit" round color="#1ab692" type="success">
            Save
          </van-button>
        </div>
      </van-popup>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { showToast } from "vant"; // 使用Vant的设备检测
// 在组件中自行实现移动端检测
const isMobileDevice = () => {
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
    navigator.userAgent
  );
};
// 头像相关逻辑
const fileInput = ref(null);
const avatarUrl = ref("");
const show = ref(false);
const showActionSheet = ref(false);

// 初始化时检测设备类型
onMounted(() => {
  isMobileDevice.value = isMobileDevice();
});
const triggerAvatarChange = () => {
  if (isMobileDevice.value) {
    // 移动端：显示选择弹窗
    showActionSheet.value = true;
  } else {
    // PC端：直接触发文件选择
    fileInput.value.click();
  }
};

// 姓名编辑相关逻辑
const NameShowNumber = ref(false);
const inputValue = ref("");
const inputNameText = ref("");
const phoneNumberText = ref("");
const inputField = ref(null);
const actions = [{ name: "Choose from gallery" }, { name: "Take photo" }];

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value.click();
};

// 处理头像更改
const handleAvatarChange = (e) => {
  const file = e.target.files[0];
  if (!file) return;

  // 验证文件类型
  if (!file.type.startsWith("image/")) {
    showToast({
      message: "请选择图片文件",
      className: "custom-toast-error",
    });
    return;
  }

  // 验证文件大小 (不超过2MB)
  if (file.size > 2 * 1024 * 1024) {
    showToast({
      message: "图片大小不能超过2MB",
      className: "custom-toast-error",
    });
    return;
  }

  // 创建文件阅读器
  const reader = new FileReader();

  reader.onload = (event) => {
    avatarUrl.value = event.target.result;
    showToast({
      message: "头像更新成功",
      className: "custom-toast-success",
    });

    // 这里可以添加上传到服务器的逻辑
    // uploadAvatar(file);
  };

  reader.onerror = () => {
    showToast({
      message: "图片读取失败",
      className: "custom-toast-error",
    });
  };

  reader.readAsDataURL(file);
};

// 处理动作表选择
const onActionSelect = (action) => {
  if (action.name === "Take photo") {
    // 移动端拍照逻辑
    if (navigator.mediaDevices?.getUserMedia) {
      // 实现拍照逻辑...
    } else {
      showToast("摄像头不可用");
    }
  } else {
    fileInput.value.click();
  }
  showActionSheet.value = false;
};
let popupTitle = ref("");
const phoneError = ref(""); // 存储电话号码验证错误信息
// Save提交
const SaveSubmit = () => {
  const value = inputValue.value.trim();
  phoneError.value = ""; // 每次提交前清空错误

  // 空值检查
  if (!value) {
    phoneError.value = "输入框不能为空";
    return;
  }

  // 根据弹窗类型处理
  if (popupTitle.value === "Edit your name") {
    inputNameText.value = value;
    showToast({
      message: "Name updated successfully",
      className: "custom-toast-success",
    });
  } else if (popupTitle.value === "Phone number") {
    // 验证是否为有效数字
    if (!/^\d+$/.test(value)) {
      phoneError.value = "请输入有效的数字";
      return;
    }

    // 验证电话号码长度
    if (value.length < 8) {
      phoneError.value = "手机号位数不能小于8位";
      return;
    }
    showToast({
      message: "Phone number updated successfully",
      className: "custom-toast-success",
    });

    phoneNumberText.value = value;
  }

  // 成功操作
  NameShowNumber.value = false;
  inputValue.value = "";
};
// 显示弹窗
const ShowFn = (name) => {
  phoneError.value = ""; // 清空错误提示
  if (name === "NameShow") {
    popupTitle.value = "Edit your name";
  } else if (name === "PhoneNumber") {
    popupTitle.value = "Phone number";
  }
  NameShowNumber.value = true;
};
const onClickLeft = () => history.back();
</script>

<style lang="scss">
.PageMypetProfile {
  .PageMypetProfile_group {
    padding: 12px;
    .van-cell-group {
      background-color: #fff;
      border-radius: 10px;
      margin: 0;
      .van-cell {
        padding: 10px 8px;
        font-weight: bold;
        font-size: 16px;
        &:first-child {
          height: 66px;
          /* 头像样式 */
          .avatar-image {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            object-fit: cover;
            background-color: #cfdadf;
          }

          .icon-user {
            width: 30px;
            height: 30px;
            background-color: #cfdadf;
            border-radius: 50%;
            text-align: center;
            line-height: 30px;
            font-size: 25px !important;
            color: #b1c0c9;
          }
        }
      }
    }
  }
}
// 弹窗样式
.van-action-sheet {
  .van-action-sheet__description {
    font-size: 20px;
    color: #000;
    font-weight: bold;
  }
  .van-action-sheet__content {
    .van-action-sheet__item {
      position: relative;
      &::after {
        position: absolute;
        box-sizing: border-box;
        content: " ";
        pointer-events: none;
        right: 16px;
        bottom: 0;
        left: 16px;
        border-bottom: 1px solid #ebedf0;
        transform: scaleY(0.5);
      }
      &:last-child::after {
        display: none;
      }
      .van-action-sheet__name {
        font-size: 16px;
        color: #000;
        font-weight: 400;
      }

      .icon-xiaofeiji {
        position: absolute;
        right: 110px;
        top: 50%;
        transform: translateY(-50%);
        font-size: 25px;
        color: #1cb58e;
      }
      .custom-action-item {
        span {
          font-size: 16px;
          color: #000;
        }
      }
    }
  }
  .van-action-sheet__gap {
    height: 20px;
  }
}
// Name 弹窗样式
.van-popup {
  .van_popup__title {
    padding: 14px;
    text-align: center;
    border-bottom: 1px solid #ccc;
  }
  .van_popup__content {
    padding: 12px;
    .van-field {
      border: 1px solid #ccc;
      border-radius: 5px;
      .van-field__right-icon {
        .van-badge__wrapper {
          font-size: 24px;
          font-weight: bold;
          color: #ccc;
        }
      }
    }
  }
  .van_popup__confirm {
    display: flex;
    justify-content: space-around;
    padding: 16px;
    button {
      width: 100%;
      font-size: 16px;
      font-weight: bold;
    }
  }
}
.custom-toast-error {
  background: rgba(255, 59, 48, 0.9);
  color: white;
  border-radius: 8px;
  padding: 12px 20px;
  z-index: 9999;
}
.custom-toast-success {
  background: rgba(40, 191, 144, 0.9);
  color: white;
  border-radius: 8px;
  padding: 12px 20px;
  z-index: 9999;
}
</style>